package net.dgg.dggcloud.service.jrcrm.service.orf;

import net.dgg.dggcloud.core.minidao.hibernate.dao.IGenericBaseCommonDao;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.iboss.service.sc.ScProOrderService;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.dao.orf.*;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.business.BusinessReferral;
import net.dgg.dggcloud.service.jrcrm.entity.business.ReferralRecord;
import net.dgg.dggcloud.service.jrcrm.entity.orf.*;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessReferralService;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 财务核款
 *
 * @author 郭伟 2017/11/2
 */
@Service
public class PaymentService extends BaseService {

    @Autowired
    private PaymentDao paymentDao;

    @Autowired
    private PayCostRecordDao payCostRecordDao;

    @Autowired
    private PerformanceDao performanceDao;


    @Autowired
    private OrderDao orderDao;

    @Autowired
    private PaymentAuditorRecordService paymentAuditorRecordService;

    @Resource
    private BusinessReferralService businessReferralService;

    @Resource
    private BusinessService businessService;

    @Autowired
    private BusinessAbilityService  businessAbilityService;

    @Resource(name="miniDaoHiberCommonDao")
    protected IGenericBaseCommonDao repository;

    /**
     *  根据ID，查询核款相关数据
     * @param id
     * @return
     */
    @Deprecated
    public OrderPayRecord getByIdHiber(Long id){
        return this.repository.get(OrderPayRecord.class,id);
    }



    public Integer countPaymentByMap(Map map) {
        return paymentDao.countPaymentByMap(map);
    }

    public List<Map> listPaymentByMap(Map map) {
        return paymentDao.listPaymentByMap(map);
    }

    /**
     *  财务核款
     * @param orderPayRecord
     * @param user
     * @return
     */
    public Long cwSavePayment(OrderPayRecord orderPayRecord,User user){
        try {
        orderPayRecord.setUpdaterUser(user);
        orderPayRecord.setPerformanceTime(new Date());
        Order order = this.repository.get(Order.class,orderPayRecord.getOrderId());
//        order.setStatus("ORF_DDZT_6");
        order.setReceivableAmount(order.getReceivableAmount() + orderPayRecord.getReceivableAmount());
        order.setAchievement(order.getAchievement()+orderPayRecord.getPerformance());
        order.setProfit(order.getProfit()+orderPayRecord.getProfit());
        order.setAmount(order.getAmount()+orderPayRecord.getAmount());
        order.setInternalCost(order.getInternalCost()+orderPayRecord.getInternalCost());
        order.setExternalCost(order.getExternalCost()+orderPayRecord.getExternalCost());
        order.setUpdaterUser(user);
        orderDao.updateByHiber(order);

//        businessAbilityService.updateBusinessOrderInfo(order.getBusinessId(),user.getId(), CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS);

        // 更新内外部成本
        Map costmap = new HashMap();
        costmap.put("paymentId",orderPayRecord.getId());
        costmap.put("type",2);
        List<Map> inCost =  payCostRecordDao.listPayCostRecordMap(costmap);
        if(null != inCost && inCost.size() > 0){
            for (int i = 0; i <inCost.size() ; i++) {
                 PaymentCostRecord pc = this.repository.get(PaymentCostRecord.class,Long.valueOf(inCost.get(i).get("id").toString()));
                pc.setIsComplete(1);
                payCostRecordDao.updateByHiber(pc);
            }
        }

        costmap.put("type",1);

        Business business  = businessService.getBusinessById(order.getBusinessId());
        Long reAmount = 0L;

        // 更新业绩数据
        List<Map> per = performanceDao.getPerformanceMap(costmap);
        if(null != per && per.size() > 0){
            for (int i = 0; i <per.size() ; i++) {
                PerformancePrefit pc = this.repository.get(PerformancePrefit.class,Long.valueOf(per.get(i).get("id").toString()));
                pc.setIsComplete(1);
                // 判断是否转介绍
                if(null != pc.getIsReferral() && pc.getIsReferral()  == 1){
                        reAmount = pc.getPerformanceAmount();
                }
                performanceDao.updateByHiber(pc);
            }
        }


            // 处理转介绍  更新记录
            if(null != business.getIsReferral() && business.getIsReferral()  == 1){
                ReferralRecord referralRecord = new ReferralRecord();
                referralRecord.setBusinessId(business.getId());
                referralRecord.setHkId(orderPayRecord.getId());
                referralRecord.setRkMoney(orderPayRecord.getAmount());
                referralRecord.setRkTime(orderPayRecord.getPerformanceTime());
                referralRecord.setPerformanceProportionMoney(reAmount);
                referralRecord.setOrderNo(order.getOrderNo());
                businessReferralService.addReferralRecord(order.getBusinessId(),referralRecord);
            }

        // 保存审核记录
        paymentAuditorRecordService.saveRecord(user,orderPayRecord.getId(),"",1,1,orderPayRecord.getStatus());
        orderPayRecord.setStatus("ORF_HKZT_5");
        paymentDao.updateByHiber(orderPayRecord);

        }catch (BizException e) {
            throw  new BizException(e.getMessage(),10001);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return orderPayRecord.getId();
    }


    /**
     *  会计核款
     * @param orderPayRecord
     * @param user
     * @return
     */
    public Long kjSavePayment(OrderPayRecord orderPayRecord,User user){
        orderPayRecord.setUpdaterUser(user);
        paymentAuditorRecordService.saveRecord(user,orderPayRecord.getId(),"",1,1,orderPayRecord.getStatus());
        orderPayRecord.setStatus("ORF_HKZT_6");
        paymentDao.updateByHiber(orderPayRecord);
        paymentAuditorRecordService.saveRecord(user,orderPayRecord.getId(),"",1,3,orderPayRecord.getStatus());
        return orderPayRecord.getId();
    }



    /**
     *
     *   行政审核
     * @param orderPayRecord   核款对象
     * @param exPayCostRecord 外部成本
     * @param inPayCostRecord  内部成本
     * @param performancePrefits 业绩利润
     * @return
     */
    public Long xzSavePayment(OrderPayRecord orderPayRecord, List<PaymentCostRecord> exPayCostRecord,List<PaymentCostRecord> inPayCostRecord,List<PerformancePrefit> performancePrefits,User user){

        orderPayRecord.setUpdaterUser(user);

        // 删除内外部成本记录
        Map costmap = new HashMap();
        costmap.put("type",2);
        costmap.put("paymentId",orderPayRecord.getId());
        payCostRecordDao.deletePayCostRecordList(costmap);

        // 保存外部成本
        if(null != exPayCostRecord && exPayCostRecord.size() > 0){
            for (int i = 0; i < exPayCostRecord.size(); i++) {
                Long exId = this.keyWorker.nextId();
                PaymentCostRecord cost = exPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(1);
                cost.setId(exId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 保存内部成本
        if(null != inPayCostRecord && inPayCostRecord.size() > 0){
            for (int i = 0; i < inPayCostRecord.size(); i++) {
                Long inId = this.keyWorker.nextId();
                PaymentCostRecord cost = inPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(2);
                cost.setId(inId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }

        costmap.put("type",1);
        // 删除业绩记录
        performanceDao.deletePerformanceList(costmap);

        //业绩利润
        if(null != performancePrefits && performancePrefits.size() > 0){
            for (int i = 0; i < performancePrefits.size(); i++) {
                Long perId = this.keyWorker.nextId();
                PerformancePrefit cost = performancePrefits.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setId(perId);
                cost.setType(1);
                User signUser =  this.repository.get(User.class,cost.getSignUserId());
                cost.setSignOrgId(signUser.getOrgId());
                cost.setOrderId(orderPayRecord.getOrderId());
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                performanceDao.saveByHiber(cost);

            }
        }

        paymentAuditorRecordService.saveRecord(user,orderPayRecord.getId(),"",1,1,orderPayRecord.getStatus());
        orderPayRecord.setStatus("ORF_HKZT_4");
        paymentDao.updateByHiber(orderPayRecord);
        return orderPayRecord.getId();
    }

    /**
     *
     *   保存核款申请
     * @param orderPayRecord   核款对象
     * @param exPayCostRecord 外部成本
     * @param inPayCostRecord  内部成本
     * @param performancePrefits 业绩利润
     * @param user 当前用户
     * @param customerName 客户名称
     * @return
     */
    public Long savePayment(OrderPayRecord orderPayRecord, List<PaymentCostRecord> exPayCostRecord,List<PaymentCostRecord> inPayCostRecord,List<PerformancePrefit> performancePrefits,User user,String customerName){


        orderPayRecord.setCreateUser(user);
        orderPayRecord.setUpdaterUser(user);

        // 保存外部成本
        if(null != exPayCostRecord && exPayCostRecord.size() > 0){
            for (int i = 0; i < exPayCostRecord.size(); i++) {
                Long exId = this.keyWorker.nextId();
                PaymentCostRecord cost = exPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(1);
                cost.setId(exId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 保存内部成本
        if(null != inPayCostRecord && inPayCostRecord.size() > 0){
            for (int i = 0; i < inPayCostRecord.size(); i++) {
                Long inId = this.keyWorker.nextId();
                PaymentCostRecord cost = inPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(2);
                cost.setId(inId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        Order order = this.repository.get(Order.class,orderPayRecord.getOrderId());
        order.setCustomerName(customerName);
        //业绩利润
        if(null != performancePrefits && performancePrefits.size() > 0){
            for (int i = 0; i < performancePrefits.size(); i++) {
                Long perId = this.keyWorker.nextId();
                PerformancePrefit cost = performancePrefits.get(i);

                if(cost.getUserType().equals("qdr")){
                    cost.setSignOrgId(order.getOrganizationId());
                }else{
                    User signUser =  this.repository.get(User.class,cost.getSignUserId());
                    cost.setSignOrgId(signUser.getOrgId());
                }
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setId(perId);
                cost.setType(1);
                cost.setOrderId(orderPayRecord.getOrderId());
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                performanceDao.saveByHiber(cost);

            }
        }

        paymentAuditorRecordService.saveRecord(user,Long.valueOf(orderPayRecord.getId()),"",1,0,"ORF_HKZT_1");
        paymentDao.saveByHiber(orderPayRecord);
        orderDao.updateByHiber(order);
        return orderPayRecord.getId();
    }


    /**
     *
     *   编辑核款申请
     * @param orderPayRecord   核款对象
     * @param exPayCostRecord 外部成本
     * @param inPayCostRecord  内部成本
     * @param performancePrefits 业绩利润
     * @param user 操作人
     * @param customerName 客户名称
     * @return
     */
    public Long updatePayment(OrderPayRecord orderPayRecord, List<PaymentCostRecord> exPayCostRecord,List<PaymentCostRecord> inPayCostRecord,List<PerformancePrefit> performancePrefits,User user,String customerName){

        orderPayRecord.setUpdaterUser(user);

        // 删除内外部成本记录
        Map costmap = new HashMap();
        costmap.put("type",2);
        costmap.put("paymentId",orderPayRecord.getId());
        payCostRecordDao.deletePayCostRecordList(costmap);

        // 保存外部成本
        if(null != exPayCostRecord && exPayCostRecord.size() > 0){
            for (int i = 0; i < exPayCostRecord.size(); i++) {
                Long exId = this.keyWorker.nextId();
                PaymentCostRecord cost = exPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(1);
                cost.setId(exId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 保存内部成本
        if(null != inPayCostRecord && inPayCostRecord.size() > 0){
            for (int i = 0; i < inPayCostRecord.size(); i++) {
                Long inId = this.keyWorker.nextId();
                PaymentCostRecord cost = inPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(2);
                cost.setStatus(2);
                cost.setId(inId);
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 删除业绩记录
        costmap.put("type",1);
        performanceDao.deletePerformanceList(costmap);

        Order order = this.repository.get(Order.class,orderPayRecord.getOrderId());
        order.setCustomerName(customerName);
        //业绩利润
        if(null != performancePrefits && performancePrefits.size() > 0){
            for (int i = 0; i < performancePrefits.size(); i++) {
                Long perId = this.keyWorker.nextId();
                PerformancePrefit cost = performancePrefits.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(orderPayRecord.getId());
                cost.setId(perId);
                cost.setType(1);
                if(cost.getUserType().equals("qdr")){
                    cost.setSignOrgId(order.getOrganizationId());
                }else{
                    User signUser =  this.repository.get(User.class,cost.getSignUserId());
                    cost.setSignOrgId(signUser.getOrgId());
                }
                cost.setOrderId(orderPayRecord.getOrderId());
                cost.setOrderBusinessId(orderPayRecord.getOrderBusinessId());
                performanceDao.saveByHiber(cost);

            }
        }

        paymentAuditorRecordService.saveRecord(user,Long.valueOf(orderPayRecord.getId()),"",1,0,orderPayRecord.getStatus());
        orderPayRecord.setStatus("ORF_HKZT_4");
        paymentDao.updateByHiber(orderPayRecord);
        orderDao.updateByHiber(order);
        return orderPayRecord.getId();
    }


    /**
     * 获取核款记录
     *  orderId  获取当前订单的核款记录
     *  orderBusinessId 获取当前生成订单的核款记录
     *  paymentId 核款ID
     * @param map
     * @return
     */
    public  List<Map> getOrderIdPaymentMap(Map map){
        return paymentDao.getOrderIdPaymentMap(map);
    }


    /**
     *  审核通过
     * @param auditUserId 当前审核人
     * @param paymentId 财务ID
     * @param isSubimtCw 是否提交给销售行政
     */
    public void saveAudit(User user,String auditUserId,String paymentId,String isSubimtCw){
        String[] paymentIds = paymentId.split(",");
        String status = "";
        if(isSubimtCw.equals("1")){

            status = "ORF_HKZT_3";
        }else{
            status = "ORF_HKZT_2";
        }
        if(null != paymentIds && paymentIds.length > 0){
            for (int i = 0; i < paymentIds.length; i++) {
                 OrderPayRecord orderPayRecord =  this.repository.get(OrderPayRecord.class,Long.valueOf(paymentIds[i]));

                if(orderPayRecord.getStatus().equals("ORF_HKZT_2")){
                    paymentAuditorRecordService.saveRecord(user,Long.valueOf(paymentId),"",1,1,orderPayRecord.getStatus());
                }else{
                    paymentAuditorRecordService.saveRecord(user,Long.valueOf(paymentId),"",1,0,orderPayRecord.getStatus());
                }

                orderPayRecord.setStatus(status);
                if(isSubimtCw.equals("1")){
                    orderPayRecord.setSaleUserId(Long.valueOf(checkAudit(auditUserId)));
                }
                orderPayRecord.setAuditUserId(Long.valueOf(checkAudit(auditUserId)));
                paymentDao.updateByHiber(orderPayRecord);

            }
        }
    }

    /**
     *  驳回操作
     * @param user
     * @param id
     * @param content
     */
    public void canelPayment(User user,String id,String content,String type){
        OrderPayRecord orderPayRecord = this.repository.get(OrderPayRecord.class,Long.valueOf(id));
        paymentAuditorRecordService.saveRecord(user,Long.valueOf(id),content,1,2,orderPayRecord.getStatus());
        orderPayRecord.setStatus("ORF_HKZT_7");
        orderPayRecord.setAuditUserId(null);
//        if(type.equals("1")){
//            orderPayRecord.setStatus("ORF_HKZT_7");
//            orderPayRecord.setAuditUserId(null);
//        }else{
//            orderPayRecord.setStatus("ORF_HKZT_3");
//            orderPayRecord.setAuditUserId(orderPayRecord.getSaleUserId());
//        }
        orderPayRecord.setRejectReason(content);
        orderPayRecord.setRejectTime(new Date());
        orderPayRecord.setUpdaterUser(user);
        paymentDao.updateByHiber(orderPayRecord);
    }


    /**
     *  获取已核款产品的总和数据
     * @param parmap
     * @return
     */
    public  Map getOrderIdProductSum(Map parmap){

        List<Map> mapList = paymentDao.getOrderIdProductSum(parmap);
        Map newMap = new HashMap();

        if(null != mapList && mapList.size() > 0){
            newMap = mapList.get(0);
        }
        return newMap;
    }


    /**
     *  获取已核款产品的列表
     * @param parmap
     * @return
     */
    public  List<Map> getOrderIdProductList(Map parmap){
        List<Map> mapList = paymentDao.getOrderIdProductList(parmap);
        return mapList;
    }

    public String checkAudit(String auditUserId){
        return auditUserId.substring(auditUserId.lastIndexOf("_")+1,auditUserId.length());
    }


    public  List<Map> getOrderBusinessMap(Long id){
        List<Map> mapList = new ArrayList<>();
        Map map =  new HashMap();
        map.put("id",123456789);
        map.put("orderBusinessNo","BM123456789");
        map.put("productName","产品1");
        map.put("trenchName","渠道1");

        mapList.add(map);
        Map map1 =  new HashMap();
        map1.put("id",123456789);
        map1.put("orderBusinessNo","BM123456789");
        map1.put("productName","产品2");
        map1.put("trenchName","渠道2");

        mapList.add(map1);
        Map map2 =  new HashMap();
        map2.put("id",123456789);
        map2.put("orderBusinessNo","BM123456789");
        map2.put("productName","产品3");
        map2.put("trenchName","渠道3");

        mapList.add(map2);
        Map map3 =  new HashMap();
        map3.put("id",123456789);
        map3.put("orderBusinessNo","BM123456789");
        map3.put("productName","产品4");
        map3.put("trenchName","渠道4");
        mapList.add(map3);
        return mapList;

    }


    /**
     *  业绩数据
     * @param map
     * @return
     */
    public  List<Map> queryPerformanceProfitExcel(Map map){
        return performanceDao.queryPerformanceProfitExcel(map);
    }

    public void updatePayment(OrderPayRecord orderPayRecord){
        paymentDao.updateByHiber(orderPayRecord);
    }

    /**
     *  贷后核款数据
     * @param map
     * @return
     */
    public  List<Map> queryLoanExcel(Map map){
        return performanceDao.queryLoanExcel(map);
    }

}
